package com.kingschan.jeasytag.tag.grid;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import org.apache.log4j.Logger;
import com.kingschan.jeasytag.container.EasyTagContainer;
import com.kingschan.jeasytag.container.impl.EasyTagContainerImpl;
import com.kingschan.jeasytag.core.format.JeasyTagFormat;
import com.kingschan.jeasytag.core.format.impl.HTMLFormatImpl;
import com.kingschan.jeasytag.core.parse.TagParseFactory;
import com.kingschan.jeasytag.enums.DbType;
import com.kingschan.jeasytag.sql.connection.ConnectionFactory;
import com.kingschan.jeasytag.sql.sqlparse.SqlMetaData;
import com.kingschan.jeasytag.tag.power.ExportTag;
import com.kingschan.jeasytag.tag.power.SearchBoxTag;
import com.kingschan.util.bean.BeanUtil;
import com.kingschan.util.encryption.MD5;
import com.kingschan.util.lang.StringUtil;
import com.kingschan.util.web.ServletUtil;

/**
 * grid model Analysis
 * 
 * @author kingschan date:2013-6-28
 */
public class GridAutoAnalysis {

	private GridTag tag;
	private static Logger log = Logger.getLogger(GridAutoAnalysis.class);
	private EasyTagContainer container=EasyTagContainerImpl.getInstance();
	private JeasyTagFormat format = new HTMLFormatImpl();
	private MD5 md5=new MD5();
	private String sfilename;
	public GridAutoAnalysis(GridTag p_gtag) {
		this.tag = p_gtag;
	}
	/**
	 * 根据sql语句  自动生成列
	 */
	public void autoBuilderColumns() throws Exception {
		if (tag.getFrozenColumns().size() + tag.getColumns().size() == 0
				&& null != tag.getSqltag()) {
			Map<String, Object> map = SqlMetaData.getColumnMetaData(tag.getSqltag().getSql(),
					DbType.valueOf(tag.getSqltag().getDBtype()),
					ConnectionFactory.getConn(tag.getSqltag().getJdbcConnection(), 
					container.getDefaultConnection()));
			Iterator<String> itera = map.keySet().iterator();
			ColumnTag ct = null;
			while (itera.hasNext()) {
				String cname = itera.next();
				ct = new ColumnTag();
				ct.setField(cname);
				ct.setTitle(cname);
				ct.setWidth("120");
				ct.setSortable("true");
				tag.addColumn(ct);
			}
			
			
		}
	}

	/**
	 * 生成列的HTML代码
	 * @throws Exception 
	 */
	public String builderColumns() throws Exception {
		// 添加普通列
		StringBuffer sb = new StringBuffer();
		if (null != tag.getColumns() && tag.getColumns().size() > 0) {
			sb.append("<thead><tr>");			
			for (int i = 0; i < tag.getColumns().size(); i++) {				
					if (null == tag.getColumns().get(i).getFrozen()
							|| "false".equals(tag.getColumns().get(i)
									.getFrozen())) {
						sb.append(format.format(tag.getColumns().get(i), tag.getPagecontent()));
						sb.append("</th>");
					} else {
						// add frezon columns
						tag.addFrozenColumns(tag.getColumns().get(i));
					}
				
				
				
			}
			sb.append("</thead></tr>");
		}

		// 如果有固定列加入固定列
		if (null != tag.getFrozenColumns() && tag.getFrozenColumns().size() > 0) {
			sb.append("<thead frozen=\"true\"><tr>");
			for (int i = 0; i < tag.getFrozenColumns().size(); i++) {
				try {
					sb.append(format.format(tag.getFrozenColumns().get(i), tag.getPagecontent()));
					sb.append("</th>");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			sb.append("</thead></tr>");
		}
		return sb.toString();
	}
	/**
	 * 导出能力
	 */
	public void addExportPower() {
		if(null!=tag.getExport()){
			try {	
				tag.addHtml(TagParseFactory.executeParse(tag.getExport(),tag.getPagecontent()));
				tag.getSuport().appendSupport(ExportTag.class);
			} catch (Exception e) {		
				e.printStackTrace();
			}
		}
	}
	/**
	 * 查询框
	 */
	public void addSearchBoxPower() {
		if (null!=tag.getSearch()) {
			try {			
				tag.addHtml(tag.getSearch().parse(tag.getSuport()));
				tag.getSuport().appendSupport(SearchBoxTag.class);
			} catch (Exception e) {			
				e.printStackTrace();
			}
		}
	}
	/**
	 * sql标签
	 */
	public void analysisSqltag() {
		//序列化数据库查询标签
		//String filename=tag.getId()+ServletUtil.getRequestURI(tag.getPagecontent())+tag.getSqltag().getSql()+tag.getSqltag().getDBtype();
		if (null!=tag.getSqltag()) {
			// filename=md5.getMD5ofStr(filename).concat(".data");
			String path=container.getSerializationPath().concat(sfilename.concat(".data"));
			try {
				if(!new File(path).exists()){
					BeanUtil.serializationObject(path, tag.getSqltag());			
				}
			} catch (IOException e) {		
				log.error(e.getMessage());
			}
		}
	}
	/**
	 * 自动构建工具条
	 */
	public void autoBuilderToolbar(){
		if (tag.getAutotoolbar()) {
			StringBuffer sb = new StringBuffer();
			sb.append("<div id=\"").append(tag.getId()).append("-toolbar\">");
			if (null!=tag.getSearch()) {
				sb.append("<a id=\"").append(tag.getId()).append("-toolbar-btn-search\"")
				.append(" href=\"javascript:open_searchbox('")
				.append(tag.getSearch().getId())
				.append("');\"")
				.append("class=\"easyui-linkbutton\" data-options=\"iconCls:'icon-search',plain:true\">查询</a>");
			}
			if (null!=tag.getExport()) {
				sb.append("<a id=\"").append(tag.getId()).append("-toolbar-btn-export\"")
				.append(" href=\"javascript:grid_export('").append(tag.getId()).append("','").append(tag.getExport().getId())
				.append("','").append(tag.getSearch().getId()).append("');\"")
				.append("class=\"easyui-linkbutton\" data-options=\"iconCls:'icon-excel',plain:true\">导出</a>");
			}
			sb.append("</div>");
			tag.addHtml(sb.toString());
		}
	}
	
	/**
	 * 分析
	 * @return
	 * @throws Exception 
	 */
	public void analysis() throws Exception{
		//工具条
		if ("auto".equals(StringUtil.ConvertNullStr(tag.getToolbar()))) {
			tag.setToolbar("#"+tag.getId().concat("-toolbar"));
			tag.setAutotoolbar(true);
		}
		
		if (null!=tag.getSqltag()) {			
			sfilename=tag.getId()+ServletUtil.getRequestURI(tag.getPagecontent())+tag.getSqltag().getSql()+tag.getSqltag().getDBtype();
			sfilename= md5.getMD5ofStr(sfilename);
			tag.addQueryParams("target", sfilename);
			tag.setUrl(ServletUtil.getApplictionRootUrl(tag.getPagecontent()).concat("/jeasytag/grid"));
			
		}			
			JeasyTagFormat format = new HTMLFormatImpl();
			tag.addHtml(format.format(tag, tag.getPagecontent()));

		
		
		
		
		
		
		
		
		
		
		//1.判断是否存在列
		if (tag.getColumns().size()==0) {
			//没有列的情况下 自动分析sql生成列
			log.debug("current grid columns size equals 0 execute auto analysis");
			this.autoBuilderColumns();			
		}
		//如果存在列   则自己解析列生成html
		tag.addHtml(this.builderColumns());
		tag.addHtml("</table>");
		//sql标签解析
		analysisSqltag();
		//导出能力
		addExportPower();
		//查询框能力
		addSearchBoxPower();
		//自动构建工具条
		autoBuilderToolbar();
	}
}
